﻿using System;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System.Collections.Generic;
using System.Text;

namespace OA.Service.SDK
{
	/// <summary>
	/// SerializationHelper 的摘要说明。
	/// </summary>
	public class SerializationHelper
	{
        private SerializationHelper()
		{}

        private static Dictionary<int, XmlSerializer> serializer_dict = new Dictionary<int, XmlSerializer>();

        public static XmlSerializer GetSerializer(Type t)
        {
            int type_hash = t.GetHashCode();

            if (!serializer_dict.ContainsKey(type_hash))
                serializer_dict.Add(type_hash, new XmlSerializer(t));

            return serializer_dict[type_hash];
        }


		/// <summary>
		/// 反序列化
		/// </summary>
		/// <param name="type">对象类型</param>
		/// <param name="filename">文件路径</param>
		/// <returns></returns>
		public static object Load(Type type, string filename)
		{
			FileStream fs = null;
			try
			{
				// open the stream...
				fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer serializer = GetSerializer(type);
                return serializer.Deserialize(fs);
			}
			catch(Exception ex)
			{
				throw ex;
			}
			finally
			{
				if(fs != null)
					fs.Close();
			}
		}


		/// <summary>
		/// 序列化
		/// </summary>
		/// <param name="obj">对象</param>
		/// <param name="filename">文件路径</param>
		public static bool Save(object obj, string filename)
		{
            bool success = false;

			FileStream fs = null;
			// serialize it...
			try
			{
				fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
				XmlSerializer serializer = new XmlSerializer(obj.GetType());
				serializer.Serialize(fs, obj);
                success = true;
			}
			catch(Exception ex)
			{
				throw ex;
			}
			finally
			{
				if(fs != null)
					fs.Close();
			}
            return success;

		}

        /// <summary>
        /// xml序列化成字符串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>xml字符串</returns>
        public static string Serialize(object obj)
        {
            System.IO.MemoryStream ms=null;
            System.IO.StreamReader sr = null;
            string result=null;
            try
            {
                XmlSerializer serializer = GetSerializer(obj.GetType());
                ms = new System.IO.MemoryStream();
                serializer.Serialize(ms, obj);
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                sr = new System.IO.StreamReader(ms);
                result = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (ms != null) ms.Close();
                else if (sr != null) sr.Close();
            }
            return result;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xmlstr">xml字符串</param>
        /// <returns>反序列化模型</returns>
        public static object DeSerialize(Type type, string xmlstr)
        {
            StringReader sr=null;
            try
            {
                XmlSerializer serializer = GetSerializer(type);
                sr = new StringReader(xmlstr);
                return serializer.Deserialize(sr);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sr != null) sr.Close();
            }
        }
        
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xmlstr">xml字符串</param>
        /// <returns>反序列化模型</returns>
        public static T DeSerialize<T>(string xmlstr)
        {
            return (T)DeSerialize(typeof(T), xmlstr);
        }

	}
}
